from Ft.Lib.CommandLine import CommandLineApp, Options, Arguments

from nodetypes.utils.OntologyImporter import OntologyImporter

class CommandLineApp(CommandLineApp.CommandLineApp):
    
    project_name = None
    project_version = None
    project_url = None

    name = 'ntoi'
    summary = ('command-line tool for importing an ontology'
               'documents')
    description = """Nodetype Ontology Importer command-line application"""
    
    defaults = {
        'container'         : '/',
        'create-container'  : False,
        'model'             : '/',
        'resource-name'     : 'index',
        'verbose'           : False,
    }

    options = [        
        Options.Option(
            'c', 'container=PATH',
            'The desired container path for storing newly created resources (default=/)'),
        Options.Option(
            'p', 'create-container',
            'Create the container if it does not already exists.'),
        Options.Option(
            'm', 'model=PATH',
            'The path of the desired model for storing ontology statements'),
        Options.Option(
            'n', 'resource-name=NAME',
            'The name of the file to use for the ontology resource (default=index)'),
        Options.Option(
            'v', 'verbose',
            'Specifiy to enable more outputs for debugging purposes.'),
        ]

    arguments = [        
        Arguments.RequiredArgument(
            'base-uri',
            'The base URI of the ontology.'),
        Arguments.RequiredArgument(
            'source-uri',
            'The URI of the RDF Ontology document to import, or "-" to indicate'
            ' standard input.'),
        ]
    
    def run(self, options, arguments):
        from myelin.utils import Repo
        
        repo = Repo.GetRepo()
        
        defaults = self.defaults
        commit = False
        try:
            cont = options.get('container',defaults['container'])
            if not repo.hasResource(cont) and \
                options.get('create-container',defaults['create-container']):
                cont = repo.createContainer(cont,1)
            else:
                cont = repo.fetchResource(
                    cont
                )
                
            oi = OntologyImporter(
                options.get('resource-name',defaults['resource-name'])
            )
            baseUri = arguments['base-uri']
            if baseUri[-1] == '#':
                baseUri = baseUri[:-1]
            if options.get('verbose',defaults['verbose']):    
                res = oi.deserializeAndFrag(
                    baseUri,
                    arguments['source-uri'],
                    cont.getAbsolutePathAsUri()+'/'
                )
                PrintResults(res)           
            
            oi.doImport(
                cont,
                baseUri,
                arguments['source-uri'],
                options.get('model',defaults['model'])
            )
            
            commit = True
            
        finally:
            if commit:
                repo.txCommit()
            else:
                repo.txRollback()
        
        
  
def PrintResults(results, stream=None):
    from Ft.Rdf.Util import SerializeStatementList
    if not stream:
        import sys
        stream = sys.stderr
        
    for rk,rv in results.items():
        stream.write("URI: %s\n" % str(rk))
        for vk,vv in rv.items():
            stream.write("  FRAG: %s\n" % vk)
            #for i in vv:
            #    print "    %s, %s" % (i, i.scope)
            stream.write(SerializeStatementList(vv))
            stream.write("\n")